package com.linln.modules.vehicle.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.linln.common.enums.ServiceTypeEnum;
import com.linln.common.utils.DateUtil;
import com.linln.common.utils.UUIDUtil;
import com.linln.common.vo.JsonResult;
import com.linln.component.cache.util.RedisUtil;
import com.linln.modules.system.domain.User;
import com.linln.modules.system.service.UserService;
import com.linln.modules.violation.service.ViolationService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linln.modules.vehicle.repository.VehicleMapper;
import com.linln.modules.vehicle.domain.Vehicle;
import com.linln.modules.vehicle.service.VehicleService;

/**
 * @author : pengliang
 * @version V1.0
 * @Project: timo
 * @Package com.linln.modules.vehicle.service.impl
 * @Descriptio /**
 * @Project: timo
 * @Package com.linln.modules.vehicle.service.impl
 * @Description: TODO
 * @date Date : 2020年12月18日 11:17
 */

@Service
public class VehicleServiceImpl extends ServiceImpl<VehicleMapper, Vehicle> implements VehicleService {

    @Autowired
    private UserService userService;

//    @Autowired
//    private YearlyInspectionService yearlyInspectionService;

    @Autowired
    private VehicleMapper vehicleMapper;

    @Autowired
    private ViolationService violationService;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public JsonResult addVehicle(Vehicle vehicle) {
        List<Vehicle> plate = this.list(new QueryWrapper<Vehicle>().eq("plate", vehicle.getPlate()));
        if (plate != null && plate.size() > 0) {
            return JsonResult.error("已存在此车辆");
        }
        if (Strings.isBlank(vehicle.getOwnerName()) || Strings.isBlank(vehicle.getOwnerMobile())) {
            User user = userService.getById(vehicle.getUserId());
            vehicle.setOwnerMobile(user.getPhone());
            vehicle.setOwnerName(user.getNickname());
        }
        //创建时间
        vehicle.setCreateTime(DateUtil.formatDate(new Date()));
        //更新时间
        vehicle.setUpdateTime(DateUtil.formatDate(new Date()));
        if (this.save(vehicle)) {
            return JsonResult.ok("添加成功");
        } else {
            return JsonResult.error("添加失败");
        }
    }

    @Override
    public Map<String, Object> getVehicleList(long userId) {
        Map<String, Object> map = new HashMap<>();
        List<Vehicle> vehicleList = this.list(new QueryWrapper<Vehicle>().eq("user_id", userId));
        vehicleList.forEach(item -> {
            Map<String, Map> vehicleInfoList = new HashMap() {{
                Map m = new HashMap() {{
                    put("verification_date", "暂无数据");
                }};
                put("xiche", m);
                put("weixiu", m);
                put("anquan", m);
                put("nianshen", m);
            }};
            //车辆最近的检测信息
            List<Map<String, Object>> VehicleServiceList = vehicleMapper.selectVehicleService(item.getPlate());
            //是否有年检信息
            AtomicReference<Object> YearlyInspection = new AtomicReference<>(item.getLatelyYearlyInspectionDate());

            VehicleServiceList.forEach(serviceInfo -> {
                //检测时间
                Timestamp timestamp = (Timestamp) serviceInfo.get("verification_date");
                //格式化检测时间
                serviceInfo.put("verification_date", DateUtil.formatDate(new Date(timestamp.getTime()), "yyyy-MM-dd"));
                switch (String.valueOf(serviceInfo.get("service_type_id"))) {
                    case ServiceTypeEnum.WASH: {
                        vehicleInfoList.put("xiche", serviceInfo);
                        break;
                    }
                    case ServiceTypeEnum.REPAIR: {
                        vehicleInfoList.put("weixiu", serviceInfo);
                        break;
                    }
                    case ServiceTypeEnum.TESTING: {
                        vehicleInfoList.put("anquan", serviceInfo);
                        break;
                    }
                    case ServiceTypeEnum.YEARRWVIEW: {
                        //如果有年审信息  保存年审时间
                        YearlyInspection.set(serviceInfo.get("verification_date"));
                        break;
                    }
                }
            });

//            YearlyInspection yearlyInspection = new YearlyInspection();
            //年检信息 当注册日期和上次年检日期不为空 才计算
            if(!Strings.isBlank(item.getRegDate()) && YearlyInspection.get()!=null){
                vehicleInfoList.put("nianshen",calculationYearlyInspection(YearlyInspection,item));
            }
//            VehicleServiceList.add(yearlyInspection);
            //违章信息
            Map<String, Object> violationInfo = new HashMap<>();
            violationInfo.put("isData", false);
            if (item.getEngineNo().length() >= 6 && item.getVinNo().length() >= 6) {
                String key = item.getPlate() + item.getEngineNo().substring(item.getEngineNo().length() - 6) + item.getVinNo().substring(item.getVinNo().length() - 6);
                Map<String, Object> resultMap = (Map<String, Object>) redisUtil.get(key);
                if (resultMap != null) {
                    violationInfo.put("isData", true);
                    violationInfo.put("totalPrice", resultMap.get("totalprice"));
                    violationInfo.put("totalScore", resultMap.get("totalscore"));
                    violationInfo.put("totalCount", resultMap.get("count"));
                    String uuid = UUIDUtil.randomUUID32();
                    redisUtil.set(uuid, key, 60 * 60 * 24);
                    violationInfo.put("id", uuid);
                }
            }

            vehicleInfoList.put("weizhang", violationInfo);
//            vehicle   InfoList.put("serviceInfo",VehicleServiceList);
//            String yiInfo = "下次年检时间为" + DateUtil.formatDate(nextYearDate, "yyyy-MM-dd") + "，还有" + distanceOfTwoDate + "天,请携带相关\n" +
//                    "材料前去年检";
//            yearlyInspection.setYiInfo(yiInfo);
//            item.setNextYearlyInspectionDay((int) distanceOfTwoDate);
            //年检信息
//            List<YearlyInspection> yearlyInspection1 = new ArrayList<>();
//            yearlyInspection1.add(yearlyInspection);
//            YearlyInspection yearlyInspection2 = yearlyInspectionService.getYearlyInspection(item.getVehicleId());
//            if (yearlyInspection2 != null) {
//                yearlyInspection1.add(yearlyInspection2);
//            }
//
//            item.setYearlyInspectionList(yearlyInspection1);


            item.setVehicleInfoList(vehicleInfoList);
        });
        map.put("data", vehicleList);
        return map;
    }



    private Map<String,Object> calculationYearlyInspection(AtomicReference<Object> yearlyInspection,Vehicle vehicle){
//        Integer regYear = Integer.parseInt(vehicle.getRegDate().substring(0,vehicle.getRegDate().indexOf("-")));
//        DateUtil.getAppointDate(,365*2);
        Map<String, Object> yearlyInfo = new HashMap<>();
        long differDay = DateUtil.getDistanceOfTwoDate(DateUtil.parseDate(vehicle.getRegDate(), "yyyy-MM-dd"), new Date());
        //车辆购买时间和现在时间距离的天数
        int year = (int)Math.floor(differDay / 365);
        //上次年审时间
        Date date = DateUtil.parseDate((String) yearlyInspection.get(), "yyyy-MM-dd");
        Date nextYearDate = null;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        //车的购买时间小于6年
        if(year <= 6){
            //每两年年审一次
            calendar.add(Calendar.YEAR,2);
            nextYearDate = calendar.getTime();
        //车的购买时间大于6年 小于等于15年
        }else if(year <= 15){
            //每年检测一次
            calendar.add(Calendar.YEAR,1);
            nextYearDate = calendar.getTime();
        //车的购买时间大于15年
        }else{
            calendar.add(Calendar.MONTH,6);
            nextYearDate = calendar.getTime();
//            nextYearDate = DateUtil.getAppointDate(date, 180);
        }


        long distanceOfTwoDate = DateUtil.getDistanceOfTwoDate(new Date(), nextYearDate);
        //下次年检天数
        yearlyInfo.put("nextYearlyInspectionDay", distanceOfTwoDate < 0 ? "0" : String.valueOf(distanceOfTwoDate));
        //可提前天数
        Calendar calendar1 = Calendar.getInstance();
        calendar.set(Calendar.YEAR,calendar1.get(Calendar.YEAR));
        calendar1.set(Calendar.MONTH,calendar.get(Calendar.MONTH));
        calendar1.add(Calendar.MONTH,-2);
        calendar1.set(Calendar.DAY_OF_MONTH,1);
        yearlyInfo.put("advanceDay", DateUtil.getDistanceOfTwoDate(calendar1.getTime(),calendar.getTime())+1);
        return yearlyInfo;
    }


    public static void main(String[] args) {
        Map<String, Object> yearlyInfo = new HashMap<>();
        Date date = DateUtil.parseDate("2020-10-28", "yyyy-MM-dd");
        Date nextYearDate = null;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH,6);
        nextYearDate = calendar.getTime();
        long distanceOfTwoDate = DateUtil.getDistanceOfTwoDate(new Date(), nextYearDate);
        //下次年检天数
        yearlyInfo.put("nextYearlyInspectionDay", distanceOfTwoDate < 0 ? "0" : String.valueOf(distanceOfTwoDate));
        //可提前天数
        Calendar calendar1 = Calendar.getInstance();
        calendar.set(Calendar.YEAR,calendar1.get(Calendar.YEAR));
        calendar1.set(Calendar.MONTH,calendar.get(Calendar.MONTH));
        calendar1.add(Calendar.MONTH,-2);
        calendar1.set(Calendar.DAY_OF_MONTH,0);
        yearlyInfo.put("advanceDay", DateUtil.getDistanceOfTwoDate(calendar1.getTime(),calendar.getTime()));
        System.out.println(yearlyInfo);
    }

    @Override
//    @Transactional
    public boolean delVehicle(String vehicleId) {
//        yearlyInspectionService.remove(new QueryWrapper<YearlyInspection>().eq("vehicle_id", vehicleId));
        return this.removeById(vehicleId);
//        return true;
    }


    @Override
    public Integer getVehicle(long userId) {
        return this.count(new QueryWrapper<Vehicle>().eq("user_id", userId));
    }


    @Override
    public Map<String, Object> getInsuranceVehicles(long userId) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("data", this.list(new QueryWrapper<Vehicle>().eq("user_id", userId)));
        return map;
    }
}
